package cn.ztydata.teachingsystem.heaven.service;

import cn.ztydata.teachingsystem.common.Page;
import cn.ztydata.teachingsystem.exception.ServiceException;
import cn.ztydata.teachingsystem.heaven.common.WebContext;
import cn.ztydata.teachingsystem.heaven.cons.Roles;
import cn.ztydata.teachingsystem.heaven.dao.NoteDao;
import cn.ztydata.teachingsystem.heaven.dao.StudentDao;
import cn.ztydata.teachingsystem.heaven.dao.TeacherDao;
import cn.ztydata.teachingsystem.heaven.dao.redis.UserNoteDao;
import cn.ztydata.teachingsystem.heaven.entity.Note;
import cn.ztydata.teachingsystem.heaven.entity.Student;
import cn.ztydata.teachingsystem.heaven.entity.Teacher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 笔记服务类
 * Created by wyh on 2015/3/19.
 */
@Service
public class NoteService extends BaseService{

    @Autowired
    private NoteDao noteDao;
    @Autowired
    private UserNoteDao userNoteDao;
    @Autowired
    private TeacherDao teacherDao;
    @Autowired
    private StudentDao studentDao;
    @Autowired
    private WebContext webContext;

    /**
     * 笔记列表
     * @param groupId 群组ID
     * @param lessonId 课程ID
     * @param page 页码
     * @param pageSize 每页条数
     * @param tag 0全部 1我的 2收藏
     * @param keyword 关键字
     * @param chapterId 章ID
     * @param nodeId 节ID
     * @return Page
     *
     * @author wyh
     * @since 2015-3-19
     */
    public Page<Note> getNoteList(long groupId, long lessonId, int page, int pageSize, int tag,  String keyword, long chapterId, long nodeId){
        //获取用户ID，角色
        long userId = webContext.getUserId();
        int role = webContext.getRole() == Roles.STUDENT ? 1 : 0;

        //收藏的
        Set<Long> favoriteSet = userNoteDao.getFavorite(userId, role);

        Page<Note> notePage = null;
        switch (tag){
            //全部
            case 0:{
                log.debug("查询全部笔记：case 0");
                notePage = noteDao.getNoteList(0, role, 1, groupId, lessonId, page, pageSize, keyword, chapterId, nodeId, null);
                break;
            }

            //我的
            case 1:{
                log.debug("查询我的笔记：case 1");
                notePage = noteDao.getNoteList(userId, role, 0, groupId, lessonId, page, pageSize, keyword, chapterId, nodeId, null);
                break;
            }

            //收藏：直接返回
            case 2:{
                log.debug("查询我的收藏笔记：case 2");
                notePage = noteDao.getNoteList(0, role, 0, groupId, lessonId, page, pageSize, keyword, chapterId, nodeId, favoriteSet);
            }
        }

        //获得笔记创建者的头像和姓名
        getNameAvatar(notePage.getItems());

        //循环遍历，看是否被收藏
        if(tag != 2) {
            log.debug("判断笔记是否被收藏：tag != 2");
            for (Note note : notePage.getItems()) {
                //收藏的不包含set为0
                if (!favoriteSet.contains(note.getId())) {
                    note.setBest(0);
                }
            }
        }

        log.debug("返回 笔记列表");
        return notePage;
    }

    /**
     * 获得笔记创建者的头像和姓名
     * @param noteList 笔记List
     *
     * @author wyh
     * @since 2015-03-25
     */
    private void getNameAvatar(List<Note> noteList){
        Set<Long> studentIds = new HashSet<>();
        Set<Long> teacherIds = new HashSet<>();

        //获取学生、老师ID
        log.debug("循环获取学生、老师ID：for(Note note : noteList)");
        for(Note note : noteList){
            if(note.getRole() == 0){
                teacherIds.add(note.getCreatorId());
            } else {
                studentIds.add(note.getCreatorId());
            }
        }

        //查询姓名和头像
        List<Teacher> teachers;
        if(!teacherIds.isEmpty()) {
            log.debug("老师ID集合不为空：!teacherIds.isEmpty()");
            teachers = teacherDao.getAllForPic(teacherIds);
        } else {
            log.debug("老师ID集合为空：else");
            teachers = new ArrayList<>();
        }
        List<Student> students;
        if(!studentIds.isEmpty()) {
            log.debug("学生ID集合不为空：!studentIds.isEmpty()");
            students = studentDao.getAllForPic(studentIds);
        } else {
            log.debug("学生ID集合为空：else");
            students = new ArrayList<>();
        }

        //循环set姓名和头像
        log.debug("循环set姓名头像：for(Note note : noteList)");
        for(Note note : noteList){
            if(note.getRole() == 0){
                for(Teacher teacher : teachers){
                    if(note.getCreatorId() == teacher.getId()){
                        note.setUserName(teacher.getName());
                        note.setUserPhoto(teacher.getPicture());
                        break;
                    }
                }
            } else {
                for(Student student : students){
                    if(note.getCreatorId() == student.getId()){
                        note.setUserName(student.getName());
                        note.setUserPhoto(student.getAvatar());
                        break;
                    }
                }
            }
        }
    }

    /**
     * 公开笔记
     * @param noteId 笔记ID
     * @param open 公开
     * @return boolean
     *
     * @author wyh
     * @since 2015-3-19
     */
    @Transactional
    public void openNote(long noteId, int open){
        //判断是否是自己创建的笔记
        if(noteDao.checkSelfNote(webContext.getUserId(), webContext.getRole() == Roles.STUDENT ? 1 : 0, noteId)){
            log.debug("笔记是自己创建的：noteDao.checkSelfNote(webContext.getUserId(), webContext.getRole() == Roles.STUDENT ? 1 : 0, noteId)");
            if(noteDao.updateOpen(noteId, open) < 1){
                log.debug("公开笔记失败：noteDao.updateOpen(noteId, open) < 1");
                throw new ServiceException("更新失败");
            }
        }
        else {
            log.debug("笔记不是自己创建的：else");
            throw new ServiceException("不可公开他人笔记");
        }
    }

    /**
     * 收藏或取消收藏
     * @param noteId 笔记ID
     * @param best 收藏
     *
     * @author wyh
     * @since 2015-3-20
     */
    public void bestNote(long noteId, int best){
        if(best == 1) {
            log.debug("收藏笔记：best == 1");
            userNoteDao.saveFavorite(webContext.getUserId(), webContext.getRole() == Roles.STUDENT ? 1 : 0, noteId);
            return;
        }
        userNoteDao.deleteFavorite(webContext.getUserId(), webContext.getRole() == Roles.STUDENT ? 1 : 0, noteId);
    }

    /**
     * 删除
     * @param noteId ID
     * @return boolean
     *
     * @author wyh
     * @since 2015-3-20
     */
    @Transactional
    public void deleteNote(long noteId){
        //判断是否是自己创建的笔记
        //判断是否是自己负责群组内的笔记
        if(noteDao.checkSelfNote(webContext.getUserId(), webContext.getRole() == Roles.STUDENT ? 1 : 0, noteId) ||
        webContext.getRole() != Roles.STUDENT && noteDao.isInGroup(noteId, webContext.getUserId()))
        {
            log.debug("笔记是自己创建的或教师负责群组内的：noteDao.checkSelfNote(webContext.getUserId(), webContext.getRole() == Roles.STUDENT ? 1 : 0, noteId)" +
                    " || webContext.getRole() != Roles.STUDENT && noteDao.isInGroup(noteId, webContext.getUserId())");
            noteDao.deleteNote(noteId);
        }
        else {
            log.debug("笔记不是自己创建的或教师负责群组内的：else");
            throw new ServiceException("当前用户没有权限删除该笔记");
        }
    }

    /**
     * 查询笔记明细
     * @param noteId 笔记ID
     * @return Note
     *
     * @author wyh
     * @since 2014-3-20
     */
    public Note getNote(long noteId){
        Note note = noteDao.getNote(noteId);
        if(note != null){
            log.debug("返回 笔记明细");
            return note;
        }
        log.warn("无记录数据：noteId->{}", noteId);
        throw new ServiceException("数据异常");
    }

    /**
     * 新增笔记
     * @param note 笔记
     *
     * @author wyh
     * @since 2014-3-20
     */
    @Transactional
    public void saveNote(Note note){
        if(webContext.getRole() == Roles.STUDENT && (note.getGroupId() == 0 || note.getGroupId() == null)){
            throw new ServiceException("非法新增");
        }
        if(noteDao.saveNote(webContext.getUserId(), webContext.getRole() == Roles.STUDENT ? 1 : 0, note) < 1){
            log.debug("新增笔记失败：noteDao.saveNote(webContext.getUserId(), webContext.getRole() == Roles.STUDENT ? 1 : 0, note) < 1");
            throw new ServiceException("新增笔记数据异常");
        }
    }

}
